<?php

namespace App\Ext;

class OSS
{
    /**
     * OSS直传回调返回参数解析
     * @param $func 回调执行方法
     */
    public function getCallBack($func) {
        $authorization = ''; # OSS的签名
        $pubKeyUrl = ''; # 公钥url
        # 注意：如果要使用HTTP_AUTHORIZATION头，你需要先在apache或者nginx中设置rewrite，以apache为例，修改
        # 配置文件/etc/httpd/conf/httpd.conf(以你的apache安装路径为准)，在DirectoryIndex index.php这行下面增加以下两行
        # RewriteEngine On
        # RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
            $authorization = base64_decode($_SERVER['HTTP_AUTHORIZATION']);
        }
        if (isset($_SERVER['HTTP_X_OSS_PUB_KEY_URL'])) {
            $pubKeyUrl = $_SERVER['HTTP_X_OSS_PUB_KEY_URL'];
        }
        if (empty($authorization) || empty($pubKeyUrl)) {
            if (isset($func['error'])) $func['error'](null, 403);
        }
        # 获取公钥
        $pubKey = curlGet($pubKeyUrl);
        if (empty($pubKey)) {
            if (isset($func['error'])) $func['error'](null, 403);
        }
        # 获取回调body
        $body = file_get_contents('php://input');
        # 拼接待签名字符串
        $authStr = '';
        $path = $_SERVER['REQUEST_URI'];
        $pos = strpos($path, '?');
        if ($pos === false) {
            $authStr = urldecode($path)."\n".$body;
        } else {
            $authStr = urldecode(substr($path, 0, $pos)).substr($path, $pos, strlen($path) - $pos)."\n".$body;
        }
        # 验证签名
        $result = openssl_verify($authStr, $authorization, $pubKey, OPENSSL_ALGO_MD5);
        if ($result == 1) {
            if (isset($func['success'])) $func['success']($body, 200);
        } else {
            if (isset($func['error'])) $func['error'](null, 403);
        }
    }
}